<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                        <el-input placeholder="请输入内容" v-model="qureyInfo.query" @clear="getUserList" clearable>
                            <el-button slot="append" icon="el-icon-search" @click="search">搜索</el-button>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="grid-content bg-purple">
                        <el-button type="primary" @click="IsAddDialog = true ">添加用户</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-table :data="userList" border>
                <el-table-column type="index" label="#"> </el-table-column>
                <el-table-column label="姓名" prop="username"> </el-table-column>
                <el-table-column label="邮箱" prop="email"> </el-table-column>
                <el-table-column label="电话" prop="mobile"> </el-table-column>
                <el-table-column label="角色" prop="role_name"> </el-table-column>
                <el-table-column label="状态" >
                    <template v-slot="slot">
<!--                        {{scope.row}}-->
                        <el-switch v-model="slot.row.mg_state" @change="userStateChange(slot.row)"/>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px" >
                    <template v-slot="slot">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(slot.row.id)"> </el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(slot.row.id)"> </el-button>
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setDialogRoleStart(slot.row)"> </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
<!--            分页-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="qureyInfo.pagenum"
                    :page-sizes="[2, 5, 10]"
                    :page-size="qureyInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
<!--        添加用户-->
        <el-dialog title="添加用户" :visible.sync="IsAddDialog" width="50%" @close="DialogClose">
<!--            内容主体-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
<!--            底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="IsAddDialog = false">取 消</el-button>
                <el-button type="primary" @click="userAdd">确 定</el-button>
            </span>
        </el-dialog>

<!--        修改用户-->
        <el-dialog
                title="修改用户"
                :visible.sync="IsEdit"
                width="50%"
                @close="editDialogClose"
        id="edit_user">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" ></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile" ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="IsEdit = false" >取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="分配角色"
                :visible.sync="setDialogRole"
                width="30%" @close="setCloseRoles"
                >
            <div>
                <p>当前用户名：{{userInfo.username}}</p>
                <p>当前角色：{{userInfo.role_name}}</p>
                <p>分配新角色：
                    <el-select v-model="selectRoleValue" placeholder="请选择">
                        <el-option
                                v-for="item in rolesList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setDialogRole = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "users",
        created() {
          this.getUserList();
        },
        data(){
            var checkEmail=(rule,value,cb)=>{
              const regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z])+/;
              if(regEmail.test(value)){
                  return cb();
              }
              cb(new Error("请输入合法的邮箱"))
            };

            return{
                qureyInfo:{
                    query:'',
                    pagenum:1,
                    pagesize:5,
                },
                userList:[],
                total:0,
                IsAddDialog:false,
                IsEdit:false,
                addForm:{
                    username:'',
                    password:'',
                    email:'',
                    mobile:''
                },
                addFormRules:{
                    username:[
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
                    ],
                    email:[
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        {validator:checkEmail,trigger: 'blur'}
                    ],
                    mobile:[
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                        { min: 1, max: 11, message: '请输入正确的手机号', trigger: 'blur' }

                    ]
                },
                editFormRules:{
                    email:[
                        {required:true,message:"请输入邮箱",trigger:'blur'},
                        {validator:checkEmail,trigger: 'blur'}
                    ],
                    mobile:[
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                        { min: 1, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
                    ]
                },
                editForm:{},
                setDialogRole:false,
                userInfo:{},
                rolesList:[],
                selectRoleValue:''
            }
        },
        methods:{
            getUserList(){
                this.$http.get('users',{params:this.qureyInfo}).then(res=>{
                    // console.log(res);
                    if(res.data.meta.status!==200){
                        return this.$message.error("数据获取失败")
                    }
                    this.userList=res.data.data.users;
                    this.total=res.data.data.total;
                    // console.log(this.userList);
                    // console.log(this.total);
                })
            },
            handleSizeChange(newSize){
                this.qureyInfo.pagesize=newSize;
                this.getUserList();
            },
            handleCurrentChange(newSize){
                this.qureyInfo.pagenum=newSize;
                this.getUserList();
            },
            userStateChange(userinfo){
                this.$http.put("users/"+userinfo.id+"/state/"+userinfo.mg_state).then(res=>{
                   // console.log(res);
                   if(res.data.meta.status!==200){
                       this.$message.error("更新失败");
                       userinfo=!userinfo;
                       return
                   }
                   this.$message.success("更新成功");
                });
                // console.log(userinfo);
            },
            search(){
                this.qureyInfo.pagenum=1;
                this.getUserList();
            },
            DialogClose(){
                this.$refs.addFormRef.resetFields();
            },
            userAdd(){
                this.$refs.addFormRef.validate(valid=>{
                    // console.log(valid);
                    if(!valid)
                        return;
                    this.$http.post('users',this.addForm).then(res=>{
                        console.log(res);
                        if(res.data.meta.status!==201){
                            this.$message.error("添加失败");
                            return
                        }
                        this.$message.success("添加成功");
                        this.IsAddDialog=false;
                        this.getUserList();

                    })

                })
            },
            editDialog(id){
                this.$http.get("users/"+id).then(res=>{
                    if(res.data.meta.status!==200){
                        return this.$message.error("查询失败");
                    }
                    this.editForm=res.data.data;
                    // console.log(this.editForm);
                });
                this.IsEdit=true;
                // console.log(id);
            },
            editDialogClose(){
                this.$refs.editFormRef.resetFields();
                this.$refs.editFormRef.clearValidate();
            },
            editUserInfo(){
                this.$refs.editFormRef.validate(vali=>{
                    if(!vali) return;
                    this.$http.put("users/"+this.editForm.id,
                        {email:this.editForm.email,mobile:this.editForm.mobile}).then(res=>{
                            // console.log(this.editForm.id);
                            if(res.data.meta.status!==200){
                                this.$message.error("更新用户数据失败");
                                return
                            }
                            this.IsEdit=false;
                            this.getUserList();
                            this.$message.success("更新用户信息成功")
                    })

                })
            },
            async removeUser(id){
                  const confirmResult=await this.$confirm("此操作将永久删除该用户，是否继续？","提示",{
                    confirmButtonText:"确定",
                    cancelButtonText:"取消",
                    type:'warning'
                }).catch(err=>err);
                if(confirmResult!=="confirm"){
                    return this.$message.info("已经取消删除");
                }
                else {
                    const {data:res}=await this.$http.delete("users/"+id);
                    if(res.meta.status!==200){
                        this.$message.error("删除失败");
                        return
                    }
                    this.$message.success("删除成功");
                    this.getUserList();
                    console.log(res);
                }
            },
            async setDialogRoleStart(userinfo){
                this.userInfo=userinfo;
                const {data:res}=await this.$http.get("roles");
                if(res.meta.status!==200){
                    return this.$message.error("获取角色列表失败")
                }
                this.rolesList=res.data;

                this.setDialogRole = true;
            },
            async saveRoleInfo(){
                if(!this.selectRoleValue){
                    return this.$message.error("请选择要分配的用户");
                }
                const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleValue});
                if(res.meta.status!==200){
                    return this.$message.error("更新角色失败");
                }
                this.$message.success("更新角色成功");
                this.getUserList();
                this.setDialogRole=false;
            },
            setCloseRoles(){
                this.selectRoleValue='';
                this.userInfo={};
            }


        }
    }
</script>

<style lang="less" scoped>
    .el-breadcrumb{
        padding-top: 15px;
        /*padding-left: 20px;*/
        .el-breadcrumb-item{
            color: white !important;
        }
    }
    .el-card{
        /*padding-top: 20px;*/
        margin-top: 15px;
        box-shadow: 5px 5px 5px #666666 !important;
    }
    #edit_user{
        position: absolute;
        right: 0;
        top: 0;
    }
</style>
